#include "FileSystem.hpp"
#include <atlstr.h>

namespace Kriko
{
	FileSystem::~FileSystem()
	{
		NameIndex::iterator i, begin = m_NameIndex.begin(), end = m_NameIndex.end();
		for (i = begin;i!=end;++i)
		{
			File* file = m_FileMgr.Dereference(i->second);
			file->UnLock();
		}
	}
	FileHandle FileSystem::GetFileRes(const char* p_FileName)
	{
		NameIndexIterator rc = m_NameIndex.insert(std::make_pair(p_FileName, FileHandle()));
		if (rc.second)
		{
			File* file = m_FileMgr.Accquire(rc.first->second);
			if (!file->Load(p_FileName))
			{
				DeleteFileRes(rc.first->second);
				rc.first->second = FileHandle();
			}
		}
		return rc.first->second;
	}
	void FileSystem::DeleteFileRes(FileHandle p_Handle)
	{
		File* file = m_FileMgr.Dereference(p_Handle);
		if (!file)
		{
			m_NameIndex.erase(m_NameIndex.find(file->m_FileName));
			file->UnLock();
			m_FileMgr.Release(p_Handle);
		}
	
	}
	bool FileSystem::File::Load(const char* p_FileName)
	{
		m_FileName = p_FileName;
		CString text = m_FileName;
		m_Handle = CreateFile((LPCWSTR)text, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if (m_Handle == INVALID_HANDLE_VALUE)
		{
			m_Handle = CreateFile((LPCWSTR)text, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
			assert(m_Handle != INVALID_HANDLE_VALUE && "Cannot Create File");
		}
		return true;
	}
	bool FileSystem::File::UnLock()
	{
		CloseHandle(m_Handle);
		return true;
	}
	void FileSystem::File::WirteToFile(const char* p_Text)
	{
		assert(SetFilePointer(m_Handle, 0, NULL, FILE_END)!=-1 && "SetFilePointer Failed");
		DWORD debug;
		assert(WriteFile(m_Handle, p_Text, strlen(p_Text), &debug, NULL) && "Cant Wirte To File");
	}
	char* FileSystem::File::ReadFormFile()
	{
		size_t size = GetFileSize(m_Handle, NULL);
		char* buffer = (char*)malloc(size);
		DWORD debug;
		assert(ReadFile(m_Handle, buffer, size, &debug, NULL) && "Cant Read Form File");
		buffer[size] = '\0';
		return buffer;
	}
}